import React, { useState, useEffect } from 'react';
import { Table, Button, Tag, Image } from 'antd';
import { Link } from 'react-router-dom';
import type { ColumnsType } from 'antd/es/table';
import { getRechargesList, type RechargesListResponse } from '@/api/modules/fund';
import { useTranslation } from 'react-i18next';

interface RechargeRecord {
  id: string;
  amount: string;
  pay_type: string;
  audit_status: string;
  created_at: string;
  voucher?: string;
}

interface LastRechargeProps {
  loading?: boolean;
}

const LastRecharge: React.FC<LastRechargeProps> = ({ loading = false }) => {
  const { t } = useTranslation();
  const [data, setData] = useState<RechargeRecord[]>([]);
  const [internalLoading, setInternalLoading] = useState(false);

  // 真实数据获取
  useEffect(() => {
    const getData = async () => {
      setInternalLoading(true);
      try {
        const response = await getRechargesList({
          _action: 'getData',
          page: 1,
          perPage: 4,
        });
        
        // 类型断言，因为axios拦截器返回的是数据而不是AxiosResponse
        const data = response as unknown as RechargesListResponse;
        
        // 转换数据格式以匹配组件期望的结构
        const rechargeData = data.items.map(item => ({
          id: item.id,
          amount: item.money || item.amount || '0',
          pay_type: item.pay_type?.toString() || 'unknown',
          audit_status: item.audit_status?.toString() || 'pending',
          created_at: item.created_at,
          voucher: item.voucher,
        }));
        
        setData(rechargeData);
      } catch (error) {
        console.error('获取充值记录失败:', error);
      } finally {
        setInternalLoading(false);
      }
    };

    getData();
  }, []);

  // 支付方式映射
  const payTypeMap: Record<string, { label: string; color: string }> = {
    alipay: { label: '支付宝', color: 'blue' },
    wechat: { label: '微信支付', color: 'green' },
    bank: { label: '银行转账', color: 'orange' }
  };

  // 审核状态映射
  const auditStatusMap: Record<string, { label: string; color: string }> = {
    approved: { label: '已通过', color: 'success' },
    pending: { label: '审核中', color: 'processing' },
    rejected: { label: '已拒绝', color: 'error' }
  };

  // 表格列配置
  const columns: ColumnsType<RechargeRecord> = [
    {
      title: t('recharge_list.table.payment_method'),
      dataIndex: 'pay_type',
      key: 'pay_type',
      render: (payType: string) => (
        <Tag color={payTypeMap[payType]?.color || 'default'}>
          {payTypeMap[payType]?.label || payType}
        </Tag>
      ),
    },
    {
      title: t('recharge_list.table.recharge_amount_usd'),
      dataIndex: 'amount',
      key: 'amount',
      render: (amount: string) => `¥${amount}`,
    },
    {
      title: t('recharge_list.table.payment_voucher'),
      dataIndex: 'voucher',
      key: 'voucher',
      render: (voucher?: string) =>
        voucher ? (
          <Image
            width={60}
            height={60}
            src={voucher}
            alt={t('recharge_list.table.payment_voucher')}
            style={{ objectFit: 'cover' }}
          />
        ) : (
          t('common.close')
        ),
    },
    {
      title: t('recharge_list.table.audit_status'),
      dataIndex: 'audit_status',
      key: 'audit_status',
      render: (status: string) => (
        <Tag color={auditStatusMap[status]?.color || 'default'}>
          {auditStatusMap[status]?.label || status}
        </Tag>
      ),
    },
    {
      title: t('recharge_list.table.created_at'),
      dataIndex: 'created_at',
      key: 'created_at',
    },
    {
      title: t('common.operate'),
      key: 'action',
      render: (_, record) => (
        <Link to={`/recharge/${record.id}`}>
          {t('common.view_details')}
        </Link>
      ),
    },
  ];

  const isLoading = loading || internalLoading;

  return (
    <div className="bg-white p-6 rounded-lg shadow">
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-xl font-bold text-blue-800">{t('route.fund_manage.recharge')}</h2>
        <Link to="/fund_manage/recharge">
          <Button type="primary">
            {t('common.back_list')}
          </Button>
        </Link>
      </div>
      <Table
        columns={columns}
        dataSource={data}
        loading={isLoading}
        pagination={false}
        rowKey="id"
        size="middle"
        scroll={{ x: 800 }}
      />
    </div>
  );
};

export default LastRecharge;